package com.safewind.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.safewind.model.User;

public class MyFilter implements Filter {

	/** 要检查的 session 的名称 */

	/** 需要排除（不拦截）的URL的正则表达式 */

	/** 检查不通过时，转发的URL */

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String servletPath = request.getServletPath();
		User userSession = (User) request.getSession().getAttribute("user");
		if (userSession == null) {
			String contextPath = request.getContextPath();
			String redirect = servletPath + "?" + request.getQueryString();
			response.sendRedirect(contextPath + "/" + "?redirect=" + URLEncoder.encode(redirect, "UTF-8"));
		} else {
			request.getSession().setAttribute("user", userSession);
			chain.doFilter(req, res);

		}
	}

	@Override
	public void init(FilterConfig cfg) throws ServletException {
	}

	@Override
	public void destroy() {

	}
}
